﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using PPAP.BO;
using System.Data;

namespace PPAP.Web.SearchReport
{
    public partial class GeneralSearch : PageBase
    {
        PPARBO bo = new PPARBO();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                btnSearch_Click(null, null);
            }
        }

        //状态显示
        public string ShowAuditStatus(string Status, string FINALSTATUS,string isinapp)
        {
            string result = "";
            result = "<span style='color:red'>已提交</span>";

            switch (Status.ToLower())
            {
                case "0":
                    if (isinapp == "0")
                        result = "<span style='color:red'>Un-allocated</span>";
                    else
                        result = "<span style='color:blue'>Allocated</span>";
                    break;
                case "1":
                    result = "<span style='color:red'>Created</span>";
                    break;
                case "2":
                    result = "<span style='color:red'>Submitted</span>";
                    break;
                case "3":
                    result = "<span style='color:red'>Ready for sampling</span>";
                    break;
                case "4":
                    result = "<span style='color:red'>Not ready for sampling</span>";
                    break;
                case "5":
                    result = "<span style='color:red'>Circulating</span>";
                    break;
                case "6":
                    if (FINALSTATUS == "0")
                        result = "<span style='color:red'>Circulating</span>";
                    else
                        result = "<span style='color:blue'>Released</span>";
                    break;
                case "7":
                    result = "<span style='color:blue'>Decided</span>";
                    break;

                default:
                    result = "<span style='color:red'></span>";
                    break;
            }
            return result;
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            try
            {
                DataSet ds = GetDataSet("");
                AspNetPager2.RecordCount = ds.Tables[0].Rows.Count;
                dgList.DataSource = GetPageTable(ds.Tables[0], AspNetPager2.PageSize, AspNetPager2.CurrentPageIndex);
                dgList.DataBind();
            }
            catch (Exception ex)
            {
                AlertMessage(ex.Message.ToString());
            }
        }

        private DataSet GetDataSet(string sort)
        {
            string sql = "";
            if (txtCreateStart.Text.Trim() != "")
                sql += " and trunc(ppardate)>=to_date( '" + txtCreateStart.Text.Trim() + "', 'yyyy-mm-dd ') ";
            if (txtCreateEnd.Text.Trim() != "")
                sql += " and trunc(ppardate)<=to_date( '" + txtCreateEnd.Text.Trim() + "', 'yyyy-mm-dd ') ";
            if (txtSupper.Text.Trim() != "")
                sql += " and lower(s.suppliername) like lower('%" + txtSupper.Text.Trim() + "%') ";
            if (txtQE.Text.Trim() != "")
                sql += " and  lower(qeuser) like lower('%" + txtQE.Text.Trim() + "%') ";
            if (ddlDocument.SelectedValue != "All")
                sql += " and iscapabilitydocument=" + ddlDocument.SelectedValue + " ";
            if (ddlPart.SelectedValue != "All")
                sql += " and iscapabilitypart=" + ddlPart.SelectedValue + " ";
            if (rbtWait.Checked)
                sql += "and a.status=6 ";
            if (rbtApproved.Checked)
                sql += " and a.status=7 ";
            if (rbtG.Checked)
                sql += " and lower(a.finalresult)='g' and a.status=7  ";
            if (rbtY.Checked)
                sql += " and lower(a.finalresult)='y' and a.status=7  ";
            if (rbtR.Checked)
                sql += " and lower(a.finalresult)='r' and a.status=7  ";
            if (RadioButton1.Checked)
                sql += " and a.status>=5 ";
            if (RadioButton2.Checked)
                sql += "  and a.status<5 ";
            if (RadioButton3.Checked)
                sql += " and a.id  in(select pparid from samplecard where 1=1 and (endtimeactual>=endtimeplan or (endtimeplan<=sysdate and status!=3 and status!=9) )  group by pparid) ";
            if (RadioButton4.Checked)
                sql += " and a.id not in(select pparid from samplecard where 1=1 and ((endtimeactual<=endtimeplan and status=3) or endtimeplan>=sysdate) group by pparid) ";
            sql += " and a.status!=9 ";
            if (ddlStatus.SelectedValue != "All")
            {
                if (ddlStatus.SelectedValue == "5")
                    sql += "  and( a.status=5 or (a.status=6 and a.FINALSTATUS=0)) ";
                else if (ddlStatus.SelectedValue == "6")
                    sql += " and a.status=6 and  a.FINALSTATUS!=0 ";
                else if (ddlStatus.SelectedValue == "-1")
                    sql += " and a.status=0 and a.isinapp=0 ";
                else if (ddlStatus.SelectedValue == "0")
                    sql += " and a.status=0 and a.isinapp=1 ";
                else
                    sql += " and a.status=" + ddlStatus.SelectedValue;

            }
            if (txtQM.Text.Trim() != "")
            {
                sql += " and lower(u.superior) like lower('%" + txtQM.Text.Trim() + "%') ";
            }
            if (chkMycase.Checked)
            {
                sql += " and   (u.superior='" + CurrentUser.Id + "'  or ((a.QuanlityEngineer='" + CurrentUser.Id + "'  or a.quanlityengineer='" + CurrentUser.Id + "' or a.quanlitymanager='" + CurrentUser.Id + "' or a.quanlityvp='" + CurrentUser.Id + "' or a.qeuser='" + CurrentUser.Id + "'  or a.id in (select pparid from samplecard where DEPTREP='" + CurrentUser.Id + "') ))) ";
            }
            sql += @" group by a.id,'PPAR-'||a.pparno||'.'||PPARVERSION ,r.bdntpartno,r.bdntpartname,r.color,a.elevel||a.qlevel ,s.suppliercode,s.suppliername,a.status, FINALRESULT,a.ppardate,a.endtime,r.bdntrevisionno,r.bdntrevisionstatus,a.decisiontext,a.explanations,
a.resubmissiondate,a.DEVIATIONEXPIREDATE,s.dsc,s.contacttel,s.address,remarks,PPARVERSION,SUPPLIERPARTNO,a.FINALSTATUS,a.isinapp ";
            sql += sort;
            DataSet ds = bo.GetListForGeneral(sql);
            return ds;
        }

        protected void AspNetPager2_PageChanged(object sender, EventArgs e)
        {
            BindGridView();
        }

        protected void btnExport_Click(object sender, EventArgs e)
        {
            try
            {
                DataSet ds = GetDataSet("");

                foreach (DataRow r in ds.Tables[0].Rows)
                {
                    r["ShowStatus"] = ShowAuditStatus(r["status"].ToString(), r["FINALSTATUS"].ToString(), r["isinapp"].ToString());
                    r["d1"] = r["PPARDATE"].ToString() == "" ? r["PPARDATE"] : DateTime.Parse(r["PPARDATE"].ToString()).ToString("yyyy-MM-dd");
                    r["d2"] = r["ENDTIME"].ToString() == "" ? r["ENDTIME"] : DateTime.Parse(r["ENDTIME"].ToString()).ToString("yyyy-MM-dd");
                }

                ds.Tables[0].Columns.Remove("ID");
                ds.Tables[0].Columns.Remove("PPARDATE");
                ds.Tables[0].Columns.Remove("ENDTIME");
                ds.Tables[0].Columns.Remove("BDNTREVISIONNO");
                ds.Tables[0].Columns.Remove("BDNTREVISIONSTATUS");
                ds.Tables[0].Columns.Remove("DECISIONTEXT");
                ds.Tables[0].Columns.Remove("EXPLANATIONS");
                ds.Tables[0].Columns.Remove("RESUBMISSIONDATE");
                ds.Tables[0].Columns.Remove("DEVIATIONEXPIREDATE");
                ds.Tables[0].Columns.Remove("DSC");
                ds.Tables[0].Columns.Remove("CONTACTTEL");
                ds.Tables[0].Columns.Remove("ADDRESS");
                ds.Tables[0].Columns.Remove("REMARKS");
               // ds.Tables[0].Columns.Remove("PPARNO1");
                ds.Tables[0].Columns.Remove("PPARVERSION");
                ds.Tables[0].Columns.Remove("SUPPLIERPARTNO");
                ds.Tables[0].Columns.Remove("FINALSTATUS");
                ds.Tables[0].Columns.Remove("ISINAPP");
                ds.Tables[0].Columns.Remove("STATUS");

                ds.Tables[0].Columns["ROWNUM"].ColumnName = "No.";
                ds.Tables[0].Columns["PPARNO"].ColumnName = "PPAR No.";
                ds.Tables[0].Columns["BDNTPARTNO"].ColumnName = "Part No.";
                ds.Tables[0].Columns["BDNTPARTNAME"].ColumnName = "Part name";
                ds.Tables[0].Columns["COLOR"].ColumnName = "Color";
                ds.Tables[0].Columns["QLEVEL"].ColumnName = "Q/E level";
                ds.Tables[0].Columns["SUPPLIERCODE"].ColumnName = "Suppiler code";
                ds.Tables[0].Columns["SUPPLIERNAME"].ColumnName = "Suppiler name";
                ds.Tables[0].Columns["ShowStatus"].ColumnName = "Status";
                ds.Tables[0].Columns["FINALRESULT"].ColumnName = "Result";
                ds.Tables[0].Columns["d1"].ColumnName = "Start date";
                ds.Tables[0].Columns["d2"].ColumnName = "End date";

                CreateExcel(ds, "General search");
            }
            catch (Exception ex)
            {
                AlertMessage(ex.Message.ToString());
            }
        }

        /// <summary>
        /// 排序
        /// </summary>
        /// <param name="source"></param>
        /// <param name="e"></param>
        protected void dgList_SortCommand(object source, DataGridSortCommandEventArgs e)
        {
            // 从事件参数获取排序数据列
            string sortExpression = e.SortExpression.ToString();

            // 假定为排序方向为“顺序”
            string sortDirection = "ASC";
            // “ASC”与事件参数获取到的排序方向进行比较，进行GridView排序方向参数的修改
            if (sortExpression == this.dgList.Attributes["SortExpression"])
            {
                //获得下一次的排序状态
                sortDirection = (this.dgList.Attributes["SortDirection"].ToString() == sortDirection ? "DESC" : "ASC");
            }
            // 重新设定GridView排序数据列及排序方向
            this.dgList.Attributes["SortExpression"] = sortExpression;
            this.dgList.Attributes["SortDirection"] = sortDirection;


            string pic = "";
            pic = sortDirection == "ASC" ? "<img src='../Images/icon/arrowup.gif' />" : "<img src='../Images/icon/arrowdown.gif' />";

            foreach (DataGridColumn item in dgList.Columns)
            {
                if (item.SortExpression == sortExpression)
                {
                    item.HeaderText = item.FooterText + " " + pic;
                }
                else
                    item.HeaderText = item.FooterText;
            }

            this.BindGridView();

        }

        private void BindGridView()
        {
            // 获取GridView排序数据列及排序方向
            string sortExpression = this.dgList.Attributes["SortExpression"];
            string sortDirection = this.dgList.Attributes["SortDirection"];
            if (sortExpression != null)
            {
                // 调用业务数据获取方法
                string sort = string.Format("  order by lower({0})  {1} ", sortExpression, sortDirection);
                if (sortExpression == "ppardate" || sortExpression == "endtime")
                {
                    sort = string.Format("  order by {0}  {1} ", sortExpression, sortDirection);
                }
                DataTable dtBind = GetDataSet(sort).Tables[0];
                // 根据GridView排序数据列及排序方向设置显示的默认数据视图
                if ((!string.IsNullOrEmpty(sortExpression)) && (!string.IsNullOrEmpty(sortDirection)))
                {
                    dtBind.DefaultView.Sort = string.Format("{0} {1}", sortExpression, sortDirection);
                }
                // GridView绑定并显示数据
                this.dgList.DataSource = GetPageTable(dtBind, AspNetPager2.PageSize, AspNetPager2.CurrentPageIndex);
                this.dgList.DataBind();
            }else
                btnSearch_Click(null, null);
        }
    }
}